//
//  XBXUIRefreshControl.swift
//  MyWeibo
//
//  Created by cat on 15/8/4.
//  Copyright © 2015年 cat. All rights reserved.
//

import UIKit
 /// 下拉刷新偏移量
private let kRefreshPullOffset: CGFloat = -60

class XBXUIRefreshControl: UIRefreshControl {
    
    // MARK: - 重写结束刷新方法
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
  
    // KVO
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0 {
            return
        }
        
        //判断是否开始刷新
        if refreshing {
            refreshView.startLoading()
        }
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag {
            refreshView.rotateFlag = true
        } else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag {
            refreshView.rotateFlag = false
            
        }
    }
    
    
    // MARK: - 构造函数
    override init() {
        super.init()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    private func setupUI() {
        // KVO 监听 frame属性变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        // 隐藏默认的转轮
        tintColor = UIColor.clearColor()
        
        // 刷新视图
        addSubview(refreshView)
        
        // 自动布局 
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        
    }
    
    
    // MARK: - 懒加载控件
    private lazy var refreshView: XBXRefreshView = XBXRefreshView.refreshView()
}

/// 下拉刷新视图,负责显示和动画
class XBXRefreshView: UIView {
    
    /// 旋转标记
    private var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
        
    }
    
    @IBOutlet weak var loadingIcon: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var tipIcon: UIImageView!
    
    
    /// 从xib中加载视图
    class func refreshView() -> XBXRefreshView {
        return NSBundle.mainBundle().loadNibNamed("XBXRefreshView", owner: nil, options: nil).last as! XBXRefreshView
    }
    
    /// 提示图标的旋转
    private func rotateTipIcon() {
        let angle = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    /// 开始加载动画
    private func startLoading() {
        // 判断动画是否已经添加
        if loadingIcon.layer.animationForKey("loadingAnim") != nil {
            return
        }
        
        // 提示隐藏视图
        tipView.hidden = true
        
        // 定义动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1.0
        // 添加动画
        loadingIcon.layer.addAnimation(anim, forKey: "loadingAnim")
    }
    
    /// 停止加载动画
    private func stopLoading() {
        tipView.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
        
    }
    
}


